# -*- coding: utf-8 -*-
""" 
@author: ertao.xyz
@create: 2021-10-09 14:47
@description: 
"""
import os
import shutil
from pathlib import Path
from fastapi import UploadFile
from .model import Files
from tempfile import NamedTemporaryFile
from utils.logger import logger
from core.settings import settings


async def save_file(user, file: UploadFile, path: str):
    '''
    文件保存
    @param username:用户名
    @param file:
    @param path:文件保存目录，从跟目录开始，‘/’开头
    @return:
    '''

    logger.info(f"用户{user.username}->上传文件:{file.filename}")

    # 本地存储临时方案，一般生产都是使用第三方云存储OSS(如七牛云, 阿里云)
    save_dir = f"{settings.BASE_PATH}{path}"
    if not os.path.exists(save_dir):
        os.mkdir(save_dir)

    try:
        suffix = Path(file.filename).suffix

        with NamedTemporaryFile(delete=False, suffix=suffix, dir=save_dir) as tmp:
            shutil.copyfileobj(file.file, tmp)
            tmp_file_name = Path(tmp.name).name
        obj = await Files.create(user=user, nickname=file.filename, filename=tmp_file_name, save_dir=save_dir,
                           url=f'http://127.0.0.1:8000/assets/{tmp_file_name}')
    except:
        return None
    finally:
        file.file.close()
        return f"http://127.0.0.1:8000/assets/{tmp_file_name}"
